package com.ocm.tourism.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ocm.tourism.core.domain.Hotel;
import com.ocm.tourism.core.domain.MapInfo;
import com.ocm.tourism.core.service.BusinessService;


@RequestMapping("/map")
@Controller
public class MapController {
    @Autowired
    BusinessService businessService;
    
    @RequestMapping(value = "/{id}/update", method=RequestMethod.POST)
    public String updateMapInfo(@PathVariable("id") Long hotelId, @Valid MapInfo mapInfo, BindingResult bindingResult, Model uiModel) {
        if (bindingResult.hasErrors()) {
            return updateMapForm(hotelId, uiModel);
         }
         Hotel hotel = businessService.findhotel(hotelId);
         hotel.addOrUpdateMapInfo(mapInfo);
         businessService.saveBusiness(hotel);
         return "redirect:/hotel/"+hotelId+"/map/show";
    }
    
    @RequestMapping(value = "/{id}/update/form", method = RequestMethod.GET)
    public String updateMapForm(@PathVariable("id")Long businessId, Model uiModel) {
       MapInfo mapInfo = businessService.findMap(businessId);
       processMap(businessId, mapInfo, uiModel);
       return "hotel/map/update";
    }
    
    private void processMap(Long businessId, MapInfo mapInfo , Model uiModel){
       if (mapInfo == null){
          mapInfo = new MapInfo();
          mapInfo.setLatitude(11.333966);
          mapInfo.setLongitude(106.052399);
       }
        uiModel.addAttribute("mapInfo", mapInfo);
        uiModel.addAttribute("businessId", businessId);
    }
}
